package com.example.loadermanager.loader

import android.content.Context
import android.database.Cursor
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.ContactsContract
import androidx.loader.app.LoaderManager
import androidx.loader.content.CursorLoader
import androidx.loader.content.Loader

class ContactsLoader(private val context: Context, val listener: (List<String>) -> Unit) :
    LoaderManager.LoaderCallbacks<Cursor> {
    private val handler = Handler(Looper.getMainLooper())
    private val list: MutableList<String> = ArrayList()
    override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> = CursorLoader(
        context,
        ContactsContract.Contacts.CONTENT_URI,
        arrayOf(
            ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME
        ),
        null,
        null,
        "${ContactsContract.Contacts.DISPLAY_NAME} asc"
    );

    override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor?) {
        if (data == null) return
        Thread {
            while (data.moveToNext()) {
                val phoneCursor: Cursor? = context.contentResolver.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                    arrayOf<String>(data.getString(data.getColumnIndex(ContactsContract.Contacts._ID))),
                    null
                )
                phoneCursor?.moveToFirst()
                list.add(
                    "${data.getString(data.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))}\n${phoneCursor?.getString(
                        phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                    )}"
                )
                phoneCursor?.close()
            }
            handler.post {
                listener(list)
            }
        }.start()

    }

    override fun onLoaderReset(loader: Loader<Cursor>) {

    }
}